package com.mine.frame.mylandemo.mvp.presenter

import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.mine.frame.common.base.BasePresenter
import com.mine.frame.common.utils.DisposableUtils
import com.mine.frame.mylandemo.mvp.iview.IMain
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Function
import io.reactivex.rxjava3.parallel.ParallelFlowable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.reactivestreams.Subscription
import java.io.BufferedReader
import java.io.FileReader
import java.io.InputStreamReader

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/15
 * Description:
 */
class MainPresenter(mIView: IMain) : BasePresenter<IMain>(mIView) {
    private var subscription: Subscription? = null


    /**
     * 获取本机IP地址
     */
    fun getNativeIP() {
        val ipStr = NetworkUtils.getIpAddressByWifi()
        mIView.showSuccess(ipStr)
        LogUtils.d("本机IP:${ipStr}")
    }

    /**
     * 获取wifi列表
     */
    fun getWifiList() {
        if (ActivityCompat.checkSelfPermission(mIView.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return
        }
        val result = NetworkUtils.getWifiScanResult().filterResults
        LogUtils.json(GsonUtils.toJson(result))
    }

    /**
     * 获取局域网内能ping的IP
     */
    fun getIPList() {
        val ipStr = NetworkUtils.getIpAddressByWifi()//192.168.1.120
        val localIPNumber = ipStr.subSequence(ipStr.lastIndexOf('.') + 1, ipStr.length)//本地的网段号
        val baseIP = ipStr.subSequence(0, ipStr.lastIndexOf('.') + 1) //变成 :192.168.1.  做为当前网段，然后进行ping
        LogUtils.d("localIP:${localIPNumber}", "ipStr:${ipStr}", "baseIP:${baseIP}")
        val ipList = arrayListOf<String>()
        subscription?.cancel()
        Flowable.range(1, 256)
                .filter { index ->
                    index.toString() != localIPNumber
                }
                .parallel(50)
                .runOn(Schedulers.io())
                .flatMap { num ->
                    val address = "${baseIP}${num}"
                    val ping = Runtime.getRuntime().exec("ping -c 1 -w 1 $address")
                    Log.e("ping  ", address)
                    if (0 == ping.waitFor()) {
                        Flowable.just(address)
                    } else {
                        Flowable.empty()
                    }
                }
                .sequential()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe {
                    this.subscription = it
                    mIView.showProgress("正在获取局域网内的IP")
                }
                .doOnNext {
                    Log.e("successful  ", "IP: $it")
                    ipList.add(it)
                }
                .doOnComplete {
                    mIView.scanIP(ipList)
                }.subscribe()
    }

    /**
     * 根据IP地址获取MAC
     */
    fun getMacFromIP(ipList: MutableList<String>) {
       /* Observable.create<MutableMap<String, String>> {
            val macMap = mutableMapOf<String, String>()
            //val exec = Runtime.getRuntime().exec("cat proc/net/arp")
            val exec = Runtime.getRuntime().exec("ip neigh show")
            exec.waitFor()
            val reader = BufferedReader(InputStreamReader(exec.inputStream))
//            val reader = BufferedReader(FileReader("/proc/net/arp"))
            Log.e("-==>" ,GsonUtils.toJson(reader))
            while (true) {
                val line = reader.readLine()
                if (line.isNullOrEmpty()) break
                Log.e("MAC-INFO: ", line)
                ipList.forEach { ip ->
                    if (line.contains(ip, true)) {
                        val mac = line.split(" +")[3]
                        macMap[ip] = mac
                    }
                }
            }
            it.onNext(macMap)
            it.onComplete()
        }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe {
                    DisposableUtils.instance.add(mIView.getDisposableTag(), it)
                }
                .doOnNext {
                    mIView.macBack(it)
                }.doOnComplete { }
                .subscribe()
*/
    }
}